package com.jiantong.web.core.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.URLConnection;

/**
 * Desc:文件处理
 * Mail:v@terminus.io
 * author:Michael Zhao
 * Date:2016-03-08.
 */
public class FUtil {

    /**
     * 根据path获取文件的contentType
     * @param path  文件路径
     * @return  返回文件ContentType
     */
    public static String contentType(String path){
        FileNameMap fileNameMap = URLConnection.getFileNameMap();

        return fileNameMap.getContentTypeFor(path);
    }

    /**
     * 拼接文件的绝对路径地址
     * @param url       文件服务地址
     * @param realPath  文件相对路径
     * @return  String
     * 返回文件的绝对路径
     */
    public static String absolutePath(String url, String realPath){
        if(realPath.startsWith("/")){
            if(url.endsWith("/")){
                return url + realPath.substring(1, realPath.length());
            }else{
                return url + realPath;
            }
        }else{
            if(url.endsWith("/")){
                return url + realPath;
            }else{
                return url + "/" + realPath;
            }
        }
    }

    /**
     * 文件上传的相对路径
     * @param path  文件上传路径
     * @return  String
     * 返回文件上传路径
     */
    public static String upPath(String path){
        return path.startsWith("/") ? path.substring(1, path.length()) : path;
    }

    public static byte[] bytes(InputStream input) throws Exception {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();

            return outputStream.toByteArray();
        }catch (IOException e){
            throw new Exception("Get file bytes info failed.", e);
        }
    }

}
